import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

public class NettyHttpServer {
    public static void main(String[] args) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup eventGroup = new NioEventLoopGroup();
        new ServerBootstrap()
                .group(bossGroup,eventGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer(){
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
//                        ch.pipeline().addLast(new HttpClientCodec());
                        ch.pipeline().addLast(new HttpObjectAggregator(65535));
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>(){
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
                                // 处理请求信息，并返回json数据
                                String result = requestMappingHandle(fullHttpRequest);

                                ByteBuf byteBuf = Unpooled.wrappedBuffer(result.getBytes(StandardCharsets.UTF_8));
                                FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,byteBuf);
                                fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");
                                fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

                                ctx.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
                            }
                        });
                    }


                })
                .bind(8080)
        ;

    }

    private static String requestMappingHandle(FullHttpRequest fullHttpRequest) {

        ByteBuf byteBuf = fullHttpRequest.content();

        System.out.println("HTTP METHOD："+fullHttpRequest.method().name());
        System.out.println("HTTP URI："+fullHttpRequest.uri());
        System.out.println(HttpHeaderNames.CONTENT_TYPE+"："+fullHttpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE));
        System.out.println("接收JSON:\n"+byteBuf.toString(CharsetUtil.UTF_8));
        return "{\"content\": \"测试 ，返回请求body\"}";
    }
}
